import SessionUtil, { JxbHttpClient } from '../../data/session/session';
import SessionSellingServerUtil from '../../data/session/sessionSellingServer';
import InteractionUtil from '../../shell/ui/interaction';
const Common = require('../../utils/common.js');
Page({
  data: {
    whole: false,
    concessional: 0,
    minus: 0,
    isShowChartChange: true,
    msg: '受不了了，商品不能再减少了哦',
    ismsg: false,
    emptyUrl: ''
  },
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: '购物车',
    });
    // this.productsLists();
    wx.removeStorageSync('specialString');
  },

  onShow: function () {
    getApp().getSaleMode()
    SessionUtil.getInstance().then(session => {
      this.queryIcon()
      this.productsLists();
      wx.removeStorageSync('specialString');
      this.setData({
        whole: false
      });
      var if_refresh = wx.getStorageSync("if_refresh");
      if (if_refresh == 3) {
        wx.setStorageSync("if_refresh", 1);
      } else if (if_refresh == 2 || if_refresh == 4) {
        wx.setStorageSync("if_refresh", 3);
      }
    })
  },
  /**
   * 点击商品前多选
   */
  checkboxChange: function (e) {
    const { item } = e.currentTarget.dataset
    var items = this.data.productsList, val = e.detail.value;
    items.map(child => {
      console.log(child.itemid)
      if (child.itemid === item) {
        child.checked = !child.checked
      }
      return child
    })
    this.setData({
      productsList: items
    });
    this.calculation()
  },
  /**
   * 点击全选
   */
  wholeChange: function (e) {
    var page = this, items = this.data.productsList;
    for (var i = 0, len = items.length; i < len; ++i) {
      items[i].checked = !page.data.whole
    }
    this.setData({
      productsList: items,
      whole: !this.data.whole
    });
    this.calculation()
  },
  golist() {
    wx.switchTab({
      url: '/pages/product/index/index'
    })
  },
  productsLists: function () {
    var page = this;
    let checkedlis = wx.getStorageSync('checkedlis');
    (new JxbHttpClient).get('AppMaster/PosCart/cartDetail').then(jxbResp=>{
      let respData = jxbResp.data, products = respData.productsList;
      if (checkedlis.length <= 0 && !checkedlis) {
        for (let i = 0; i < products.length; i++) {
          products[i].checked = true;
        }
      } else {
        for (let i = 0; i < products.length; i++) {
          if (Common.contains(checkedlis, products[i].itemid)) {
            products[i].checked = true;
          } else {
            products[i].checked = false;
          }
        }
      }
      this.setData({
        productsList: products,
      })
      this.calculation()
    }).catch(err=>{
      console.log(err)
      wx.showToast({
        title: err.message,
        icon: 'none',
        duration: 2000
      })
      this.setData({
        productMaskClass: "",
        productsList: {},
        isShowChartChange: false
      })
    })
  },
  /**
   * 计算已选的总值
   */
  calculation: function () {
    var items = this.data.productsList, original = 0, minus = 0, concessional = 0, checkedlis = [], j = 0, whole = true, len = 0;
    for (var i = 0, len = items.length; i < len; ++i) {
      if (items[i].checked) {
        original += (items[i].memberPrice * items[i].carNumber)
        concessional += (items[i].show_price * items[i].carNumber)
        checkedlis[j] = items[i].itemid
        j++
      } else {
        whole = false
      }
    }
    wx.setStorageSync('checkedlis', checkedlis);
    if (len < 1) {
      this.setData({
        whole: false,
        isShowChartChange: false
      })
    } else {
      minus = original - concessional;
      minus = Math.round(minus * 100) / 100
      concessional = Math.round(concessional * 100) / 100
      this.setData({
        concessional: concessional,
        minus: minus,
        checkedlis: checkedlis,
        whole: whole,
        isShowChartChange: true
      })
    }

  },
  /**
   * 商品量加一
   */
  shoppingCartAdd: function (e) {
    var page = this;
    var a = e.currentTarget.id,
    [itemId, index] = a.split('_');
    JxbHttpClient.getClient().post({
      url:'/AppMaster/PosCart/PosAddCart',
      data: {
        number: 1,
        itemId: itemId
      }
    }).then(jxbResp=>{
      var prodList = this.data.productsList
      prodList[index].carNumber = prodList[index].carNumber + 1
      page.setData({
        productsList: prodList,
      })
      page.calculation();
    }).catch(err=>{
      InteractionUtil.showNotice(err.message)
    })
  },
  /**
   * 商品量减一
   */
  shoppingCartReduce: function (e) {
    var itemId = e.currentTarget.id;
    let [cartId, num, index] = itemId.split('_');
    num = num - 1;
    if (num < 1) {
      InteractionUtil.showNotice(this.data.msg);
    } else {
      JxbHttpClient.getClient().post({
        url: '/AppMaster/PosCart/PosUpdate',
        data: {
          number: num,
          cartId: cartId
        },
      }).then(jxbResp=>{
        var prodList = this.data.productsList
        prodList[index].carNumber = num
        this.setData({
          productsList: prodList
        })
        this.calculation()
      }).catch(err=>{
        InteractionUtil.showNotice(err.message)
      })
    }
  },
  /**
   * 商品删除
   */
  deletecart: function (e) {
    var page = this;
    var a = e.currentTarget.id,
      cartId = a.split('_')[0],
      index = a.split('_')[1];
    wx.showModal({
      content: '确认要删除该商品吗？',
      cancelText: '我再想想',
      cancelColor: '#888',
      success: function (res) {
        if (res.confirm) {
          Common.my_request({
            url: '/AppMaster/PosCart/PosDelete', //仅为示例，并非真实的接口地址
            data: {
              cartId: cartId
            },
            success: function (res) {
              if (res.data.result == 0) {
                var List = page.data.productsList
                List.splice(index, 1);
                page.setData({
                  productsList: List
                })
                page.calculation()
              }
            }
          });
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  /**
   * 去详情
   */
  goDetail: function (e) {
    var itemId = e.currentTarget.id;
    this.setData({
      Details: false,
    })
    wx.navigateTo({
      url: '/pages/product/detail/detail?itemId=' + itemId
    })
  },
  /**
   * 去结算
   */
  goOrderConfirm: function () {
    wx.setStorageSync("if_refresh", 2);
    var _this = this,
      userid = wx.getStorageSync('user_id');
    if (_this.data.productsList.length < 1) {
      Common.Alert("提示", "亲，您还没有添加商品哦!");
      return false;
    }
    if (_this.data.checkedlis.length < 1) {
      Common.Alert("提示", "亲，您还没有选择商品哦!");
      return false;
    }
    if (userid < 0) {
      wx.navigateTo({
        url: '/pages/my/logintype/logintype?from=6&checkedlis=' + _this.data.checkedlis
      });
    } else {
  
      wx.navigateTo({
        url: '/pages/product/orderConfirm/index?checkedlis=' + _this.data.checkedlis
      });
    }
  },
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
  }, 
  queryIcon () {
    SessionSellingServerUtil.getInstance().then(sellingServer => {
      this.setData({
        emptyUrl: sellingServer.getTheAgentSync().emptyShopCartBgUri
      })
    })
  }
})